<template>
  <div class="webrtc-player">
    <video 
      id="webrtcVideo"
      ref="videoElement"
      controls 
      autoplay
      muted
      style="object-fit: fill; width: 100%; max-width: 800px;"
    ></video>
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
    <div v-if="!streamActive && !error" class="status-info">
      视频未连接
    </div>
  </div>
</template>

<script>
export default {
  name: 'WebRTCPlayer',
  props: {
    // webrtc-streamer服务地址，例如 'http://localhost:8000'
    serverUrl: {
      type: String,
      required: true
    },
    // 海康摄像头的RTSP地址
    rtspUrl: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      webRtcServer: null,
      streamActive: false,
      error: ''
    };
  },
  mounted() {
    this.initWebRtcPlayer();
  },
  beforeUnmount() {
    this.disconnect();
  },
  methods: {
    initWebRtcPlayer() {
      // 确保引入webrtcstreamer.js，例如在public/index.html中通过<script>引入
      if (typeof WebRtcStreamer === 'undefined') {
        this.error = 'WebRTC流播放库未加载';
        return;
      }
      
      try {
        // 初始化webrtc-streamer连接
        this.webRtcServer = new WebRtcStreamer("webrtcVideo", this.serverUrl);
        // 连接RTSP流
        this.webRtcServer.connect(this.rtspUrl);
        this.streamActive = true;
        this.error = '';
        
      } catch (err) {
        this.error = '播放器初始化失败: ' + err.message;
        console.error(err);
      }
    },
    disconnect() {
      if (this.webRtcServer) {
        this.webRtcServer.disconnect();
        this.webRtcServer = null;
      }
      this.streamActive = false;
    }
  },
  watch: {
    // 当serverUrl或rtspUrl变化时，重新初始化播放器
    serverUrl: {
      handler: 'initWebRtcPlayer',
      immediate: false
    },
    rtspUrl: {
      handler: 'initWebRtcPlayer',
      immediate: false
    }
  }
};
</script>

<style scoped>
.webrtc-player {
  position: relative;
}
.error-message {
  color: #f56c6c;
  text-align: center;
  padding: 10px;
  background-color: #fef0f0;
}
.status-info {
  text-align: center;
  padding: 10px;
  color: #909399;
}
</style>